<?php
namespace Icsoc\SecurityBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class UploadDownloadCommand
 * @package Icsoc\SecurityBundle\Command
 */
class UploadDownloadCommand extends ContainerAwareCommand
{

    /** @var \Doctrine\DBAL\Connection $conn */
    private $conn;
    //请求地址
    private $url = 'http://export.icsoc.net/export';
    //请求参数
    private $params;

    protected function configure()
    {
        $this
            ->setName('upload:download')
            ->setDescription('更新完成进度');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->conn =  $this->getContainer()->get('doctrine.dbal.default_connection');
        $this->updateProgress();
    }

    /**
     *
     */
    protected function updateProgress()
    {
        $data = $this->conn->fetchAll('SELECT token_id FROM win_download_log WHERE progress<100');
        if (empty($data)) {
            return;
        }
        foreach ($data as $val) {
            $this->params .= $val['token_id'].',';
        }
        $this->params = 'token_id='.rtrim($this->params, ',');
        $progress = $this->request($this->url, $this->params);
        $progress = json_decode($progress);
        foreach ($progress->result as $key => $val) {
            if (empty($val)) {
                $logFile1 = "/var/log/manage/security_uploaddownload_".date('Y-m-d').".txt";
                file_put_contents($logFile1, 'token_id='.$key.'的任务不存在'."\r\n", FILE_APPEND);
                continue;
            }
            $nowProgress = $val->progress;
            $this->conn->update('win_download_log', array('progress' => $nowProgress), array('token_id' => $key));
        }
    }

    /**
     * @param $url
     * @param $params
     * @return array|bool
     */
    protected function request($url, $params)
    {
        $url .=  '?'.$params;

        return file_get_contents($url);
    }
}
